<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import Poster from '@/components/poster.vue'
	import {
		getInfoApi
	} from "@/assets/api/other/login.js"
	import {
		getTickApi
	} from "@/assets/api/other/recommend.js"
	import {
		baseUrl,
		appid,
		h5Title
	} from "@/config/index.js"
	import {
		hex_sha1
	} from '@/assets/scripts/sha1.js'
	import post from '@/assets/pic/recommend/post.png'
	import {
		navigateBack
	} from "@/assets/scripts/navigate.js"

	const posterRef = ref()
	const posterImage = ref('')
	const title = ref('邀请您创建纪念馆')
	const tip = ref('您成功建馆后双方分别奖励9.9元等值缅怀币')
	const userInfo = ref({})
	const qrcode = ref('')

	// 生成签名
	function generateSignature(params) {
		const sortedKeys = Object.keys(params).sort()
		const sortedParams = []
		sortedKeys.forEach(key => {
			sortedParams.push(`${key}=${params[key]}`)
		})
		return hex_sha1(sortedParams.join('&')).toString()
	}

	// 海报生成成功回调
	const onPosterSuccess = (imageUrl) => {
		// console.log(imageUrl);
		posterImage.value = imageUrl
		uni.showToast({
			title: '海报生成成功',
			icon: 'success'
		})
	}

	// 海报生成失败回调
	const onPosterError = (error) => {
		uni.showToast({
			title: '海报生成失败',
			icon: 'error'
		})
		console.error(error)
	}

	// 保存图片到相册
	const handleSave = () => {
		if (!posterImage.value) {
			uni.showToast({
				title: '请先生成海报',
				icon: 'none'
			})
			return
		}

		// 预览图片
		uni.previewImage({
			urls: [posterImage.value],
			longPressActions: {
				itemList: ['发送给朋友', '保存图片', '收藏'],
				success: function(data) {
					console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
					// 在H5环境下提示长按保存
					uni.showToast({
						title: '请长按海报保存',
						icon: 'none'
					})
				},
				fail: function(err) {
					console.log(err.errMsg);
				}
			}
		});


	}

	// 分享功能
	const handleShare = () => {
		if (!posterImage.value) {
			uni.showToast({
				title: '海报生成中，请稍后',
				icon: 'none'
			})
			return
		}

		jWeixin.ready(function() {
			jWeixin.updateAppMessageShareData({
				title: title.value,
				desc: tip.value,
				link: qrcode.value,
				imgUrl: userInfo.value.avatar,
				success: function() {
					uni.showToast({
						title: '请点击右上角分享',
						icon: 'success',
					})
				},
				fail: function() {
					uni.showToast({
						title: '分享配置失败',
						icon: 'error'
					})
				}
			})
		})
	}

	onMounted(async () => {
		await userInfo_init()
		await qrcode_init()
		wxJSSDK_init()
	})

	// 初始化用户信息
	const userInfo_init = async () => {
		const res = await getInfoApi()
		if (res.code === 200) {
			userInfo.value = res.user
			uni.setStorageSync('user', res.user)
		} else {
			uni.showToast({
				title: '获取用户信息失败',
				icon: 'error',
			})
		}
	}

	// 初始化二维码链接
	const qrcode_init = () => {
		qrcode.value = baseUrl + `/pages/others/login?pageParams=` +
			`/pages/others/recommend/result?userId=${userInfo.value?.userId || ''}`
	}

	// 初始化微信JS-SDK
	const wxJSSDK_init = async () => {
		const res = await getTickApi()
		if (res.code !== 200) {
			uni.showToast({
				title: '请求失败,请刷新页面',
				icon: 'error'
			})
			return
		}

		const jsapi_ticket = res.data
		const timestamp = parseInt(new Date().getTime() / 1000) + ''
		const str = timestamp.slice(0, 6)
		const nonceStr = str + 'ABCD' + str
		const url = baseUrl + '/pages/others/recommend/create'
		const params = {
			noncestr: nonceStr,
			jsapi_ticket,
			timestamp,
			url,
		}
		const signature = generateSignature(params)

		jWeixin.config({
			debug: false,
			appId: appid,
			timestamp,
			nonceStr,
			signature,
			jsApiList: ['updateAppMessageShareData']
		})

		jWeixin.ready(function() {
			console.log('微信JS-SDK配置成功')
		})

		jWeixin.error((err) => {
			console.error('微信JS-SDK配置失败:', err)
			uni.showToast({
				title: '分享功能配置失败',
				icon: 'error'
			})
		})
	}
</script>

<template>
	<view>
		<uv-navbar :fixed="false" bgColor="#ff5000" leftIconColor="#fff" :titleStyle="{color:'#fff'}"
			@leftClick="navigateBack" :title="h5Title">
		</uv-navbar>

		<!-- 海报组件 -->
		<Poster v-if="qrcode" ref="posterRef" :avatar="userInfo.avatar || ''" :nickName="userInfo.nickName || ''"
			:title="title" :postImage="post" :tip="tip" :qrcodeUrl="qrcode" :width="750" :ratio="0.5"
			@ok="onPosterSuccess" @error="onPosterError" />

		<!-- 操作按钮 -->
		<view class="p-big box">
			<uv-button @click="handleSave" text="保存至相册" shape="circle"
				color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))">
			</uv-button>
			<uv-button @click="handleShare" text="分享给朋友" shape="circle" class="mt-normal"
				color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))">
			</uv-button>
		</view>
	</view>
</template>

<style lang="scss" scoped>
	.box {
		background-color: #ff971b;
		padding-bottom: 20px;
	}

	.mt-normal {
		margin-top: 16px;
	}

	.p-big {
		padding: 20px;
	}
</style>